package com.bcmusic.music.service.impl;

import com.bcmusic.file.feign.FileFeign;
import com.bcmusic.music.dao.MusicMapper;
import com.bcmusic.music.domain.music.dto.UploadMusicDTO;
import com.bcmusic.music.domain.music.vo.CertificateVO;
import com.bcmusic.music.domain.music.vo.DownLoadMusicVO;
import com.bcmusic.music.domain.music.vo.UpLoadedMusicVO;
import com.bcmusic.music.pojo.Music;
import com.bcmusic.music.service.MusicService;
import com.bcmusic.user.feign.UserFeign;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import entity.SmartBeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/****
 * @Author:admin
 * @Description:Music业务层接口实现类
 * @Date 2019/6/14 0:16
 *****/
@Service
public class MusicServiceImpl implements MusicService {

    @Autowired
    private MusicMapper musicMapper;

    @Autowired
    private FileFeign fileFeign;

    @Autowired
    private UserFeign userFeign;

    /**
     * Music条件+分页查询
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public PageInfo findPage(int page, int size, String userNum){
        //分页
        PageHelper.startPage(page,size);
        Music music=new Music();
        music.setOwnerNumber(userNum);
        //已经撤销的不显示
        music.setValidStatus(-3);
        //搜索条件构建
        Example example = createStatusExample(music);
        //执行搜索
        List<Music> list = musicMapper.selectByExample(example);
        Random random=new Random(10);
        List<UpLoadedMusicVO> upLoadedMusicVOS = SmartBeanUtil.copyList(list, UpLoadedMusicVO.class);
        for (int i = 0; i < upLoadedMusicVOS.size(); i++) {
            System.out.println(1000*(int)(Math.random()*10+1));
            upLoadedMusicVOS.get(i).setEarnings(new BigDecimal(String.valueOf(1000*Math.random())));
            upLoadedMusicVOS.get(i).setEarnings(upLoadedMusicVOS.get(i).getEarnings().setScale(2, BigDecimal.ROUND_HALF_UP));
            upLoadedMusicVOS.get(i).setCopyrightRegistrationNumber(getSHA256StrJava(upLoadedMusicVOS.get(i).getMusicName()));
        }
        return new PageInfo(upLoadedMusicVOS);
    }

    /**
     * Music分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageInfo<Music> findPage(int page, int size){
        //静态分页
        PageHelper.startPage(page,size);
        //分页查询
        return new PageInfo<Music>(musicMapper.selectAll());
    }

    /**
     * Music条件查询
     * @param music
     * @return
     */
    @Override
    public List<Music> findList(Music music){
        //构建查询条件
        Example example = createExample(music);
        //根据构建的条件查询数据
        return musicMapper.selectByExample(example);
    }

    public Example createStatusExample(Music music){
        Example example=new Example(Music.class);
        Example.Criteria criteria = example.createCriteria();
        if(music!=null){
            // 版权方编号。关联user表的user_number字段。
            if(!StringUtils.isEmpty(music.getOwnerNumber())){
                criteria.andEqualTo("ownerNumber",music.getOwnerNumber());
            }
            // 音乐审核状态。0默认为待审核，1为登记成功，-1为审核不通过。-2为已过期，-3为已撤销
            if(!StringUtils.isEmpty(music.getValidStatus())){
                criteria.andNotEqualTo("validStatus",music.getValidStatus());
            }
        }
        return example;
    }

    /**
     * Music构建查询对象
     * @param music
     * @return
     */
    public Example createExample(Music music){
        Example example=new Example(Music.class);
        Example.Criteria criteria = example.createCriteria();
        if(music!=null){
            // 音乐id。
            if(!StringUtils.isEmpty(music.getMusicId())){
                    criteria.andEqualTo("musicId",music.getMusicId());
            }
            //
            if(!StringUtils.isEmpty(music.getMusicName())){
                    criteria.andEqualTo("musicName",music.getMusicName());
            }
            // 专辑名称
            if(!StringUtils.isEmpty(music.getAlbumName())){
                    criteria.andEqualTo("albumName",music.getAlbumName());
            }
            // 唱片公司
            if(!StringUtils.isEmpty(music.getRecordCompany())){
                    criteria.andEqualTo("recordCompany",music.getRecordCompany());
            }
            // 出版公司
            if(!StringUtils.isEmpty(music.getPublishingCompany())){
                    criteria.andEqualTo("publishingCompany",music.getPublishingCompany());
            }
            // 版权方编号。关联user表的user_number字段。
            if(!StringUtils.isEmpty(music.getOwnerNumber())){
                    criteria.andEqualTo("ownerNumber",music.getOwnerNumber());
            }
            // 0为歌曲，1为曲谱
            if(!StringUtils.isEmpty(music.getMusicType())){
                    criteria.andEqualTo("musicType",music.getMusicType());
            }
            // 演唱者
            if(!StringUtils.isEmpty(music.getSinger())){
                    criteria.andEqualTo("singer",music.getSinger());
            }
            // 音乐作品地址。
            if(!StringUtils.isEmpty(music.getMusicAddress())){
                    criteria.andEqualTo("musicAddress",music.getMusicAddress());
            }
            // 作曲家
            if(!StringUtils.isEmpty(music.getComposer())){
                    criteria.andEqualTo("composer",music.getComposer());
            }
            // 曲谱文件
            if(!StringUtils.isEmpty(music.getOpernFile())){
                    criteria.andEqualTo("opernFile",music.getOpernFile());
            }
            // 歌词作者
            if(!StringUtils.isEmpty(music.getLyricist())){
                    criteria.andEqualTo("lyricist",music.getLyricist());
            }
            // 歌词文件地址
            if(!StringUtils.isEmpty(music.getLyricsFile())){
                    criteria.andEqualTo("lyricsFile",music.getLyricsFile());
            }
            // 音乐审核状态。0默认为待审核，1为登记成功，-1为审核不通过。-2为已过期，-3为已撤销
            if(!StringUtils.isEmpty(music.getValidStatus())){
                    criteria.andEqualTo("validStatus",music.getValidStatus());
            }
            // 音乐审核时间。管理员/系统审核上传的音乐的时间。
            if(!StringUtils.isEmpty(music.getCheckTime())){
                    criteria.andEqualTo("checkTime",music.getCheckTime());
            }
            //
            if(!StringUtils.isEmpty(music.getAuditorNumber())){
                    criteria.andEqualTo("auditorNumber",music.getAuditorNumber());
            }
            // 音乐上传时间。
            if(!StringUtils.isEmpty(music.getUploadTime())){
                    criteria.andEqualTo("uploadTime",music.getUploadTime());
            }
        }
        return example;
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(Integer id){
        musicMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改Music
     * @param music
     */
    @Override
    public void update(Music music){
        musicMapper.updateByPrimaryKey(music);
    }

    /**
     * 增加Music
     * @param music
     */
    @Override
    public void add(Music music){
        musicMapper.insert(music);
    }

    /**
     * 根据ID查询Music
     * @param id
     * @return
     */
    @Override
    public Music findById(Integer id){
        return  musicMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询Music全部数据
     * @return
     */
    @Override
    public List<Music> findAll() {
        return musicMapper.selectAll();
    }

    /**
     * 上传音乐
     * @param music
     * @param userNum
     * @return
     */
    @Override
    public int uploadMusic(UploadMusicDTO music,String userNum) {
        Music newMusic = SmartBeanUtil.copy(music, Music.class);
        newMusic.setOwnerNumber(userNum);
        newMusic.setUploadTime(new Date());
        return musicMapper.insertSelective(newMusic);
    }

    /**
     * 撤销音乐
     * @param musicId
     * @param userNum
     * @return
     */
    @Override
    public int backOutMusic(Integer musicId, String userNum) {
        Music music=new Music();
        music.setMusicId(musicId);
        Music oldMusic = musicMapper.selectByPrimaryKey(musicId);
        if(oldMusic==null||!oldMusic.getOwnerNumber().equals(userNum)||oldMusic.getValidStatus()==1||oldMusic.getValidStatus()==-3){
            return 0;
        }
        oldMusic.setValidStatus(-3);
        return musicMapper.updateByPrimaryKeySelective(oldMusic);
    }

    /**
     * 获取证书
     * @param musicId
     * @param userNum
     * @return
     */
    @Override
    public CertificateVO getCertificateVO(Integer musicId, String userNum) {
        Music music = musicMapper.selectByPrimaryKey(musicId);
        //不是这个人的,没权限
        if(music==null||!music.getOwnerNumber().equals(userNum)){
            return null;
        }
        CertificateVO certificate = SmartBeanUtil.copy(music, CertificateVO.class);
        String data = (String)userFeign.getRealName().getData();
        if(data==null){
            return null;
        }
        certificate.setOwnerName(data);
        certificate.setAuthorizationCode(new BCryptPasswordEncoder().encode(String.valueOf(musicId)));
        return certificate;
    }



    @Override
    public DownLoadMusicVO downLoadMusic(Integer musicId, String userNum) {
        Music music = musicMapper.selectByPrimaryKey(musicId);
        if(music==null||!music.getOwnerNumber().equals(userNum))
        {
            return null;
        }
        return SmartBeanUtil.copy(music,DownLoadMusicVO.class);
    }

    @Override
    public List<CertificateVO> getMusicInfo(List<Integer> musicIdList) {

        List<CertificateVO>list=new ArrayList<>();
        List<String>userNumList=new ArrayList<>();
        for (int i = 0; i < musicIdList.size(); i++) {
            Music music = musicMapper.selectByPrimaryKey(musicIdList.get(i));
            CertificateVO certificate = SmartBeanUtil.copy(music, CertificateVO.class);
            certificate.setAuthorizationCode(new BCryptPasswordEncoder().encode(String.valueOf(musicIdList.get(i))));
            list.add(certificate);
            userNumList.add(music.getOwnerNumber());
        }

        //不对，这逻辑怪怪的
        List<String> realNameList=userFeign.getRealNameList(userNumList).getData();

        for (int i = 0; i < list.size(); i++) {
            list.get(i).setOwnerName(realNameList.get(i));
        }
        return list;
    }

    @Override
    public List<Music> getMusicByIdList(List<Integer> idList) {

        List<Music>musicList=new ArrayList<>();
        //这里批量查询解决不了排序问题
        for (int i = 0; i < idList.size(); i++) {
            Music music = musicMapper.selectByPrimaryKey(idList.get(i));
            musicList.add(music);
        }
        return musicList;
    }

    @Override
    public String uploadFile(MultipartFile file) {
        String upload = fileFeign.upload(file);
        return upload;
    }

    /**
     * 检查是不是mp3类型
     * @return
     */
    public boolean checkType(MultipartFile file)
    {
        if(file.isEmpty()){
            return false;
        }
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!suffix.equals("mp3")) {
            return false;
        }
        return true;
    }

    public static String getSHA256StrJava(String str) {

        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encodeStr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodeStr;
    }

    private static String byte2Hex(byte[] bytes) {
        System.out.println(bytes.length);
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i = 0; i < bytes.length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1) {
                // 1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }


}
